<template>
    <div class="column">
        <div class="padding margin-bottom">
            <toolbar
                class="bg-white"
                :question="question"
                :input.sync="query.searchStr"
                :type.sync="searchType"
                @click="Operator"
                @change="Query"
            />
        </div>

        <div class="flex1 padding">
            <el-table ref="table" :data="tableData" style="width:100%" :row-key="RowKey">
                <el-table-column type="selection" :reserve-selection="true" />
                <el-table-column label="序号" align="center" type="index" />
                <el-table-column
                    v-for="(item,index) in tableHeader"
                    :key="index"
                    align="center"
                    :prop="item.prop"
                    :label="item.label"
                />
                <el-table-column align="center" label="操作">
                    <template slot-scope="scope">
                        <el-button v-if="layout=='常见问题'" type="text" @click="View(scope)">查看</el-button>
                        <el-button type="text" @click="OpenDialog(scope)">编辑</el-button>
                        <el-button type="text" @click="Del(scope)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pag :total="total" @change="PagChange" />
        </div>

        <el-dialog :visible.sync="dialogVisible" width="30%" center @closed="Close">
            <h3 slot="title">{{ dialog.title }}</h3>
            <el-form ref="form" :model="dialog" @submit.native.prevent>
                <el-form-item
                    v-if="layout==='城市档案'||layout==='常见问题'"
                    class="dialog-title"
                    prop="provice"
                    :rules="layout==='城市档案'?null:rules"
                >
                    <el-input
                        v-model.trim="dialog.provice"
                        :disabled="readonly"
                        :placeholder="layout==='城市档案'?'请输入省/直辖市/自治区名':'请输入问题标题'"
                        :maxlength="limit[1]"
                    />
                </el-form-item>
                <el-form-item prop="input" :rules="rules">
                    <el-input
                        v-model="dialog.input"
                        :disabled="readonly"
                        type="layout==='常见问题'?'textarea':'text'"
                        :rows="5"
                        :placeholder="dialog.placeholder"
                        :maxlength="limit[0]"
                    />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="Edit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
/*
弹窗流程:
    1. 打开dialog,相关数据塞进this.dialog做中转;
    2.Edit、Del || Export 从this.dialog里拿数据
*/
import toolbar from '../module/toolbar'
import pag from '@/components/public/Pagination'
import { remote } from '@/api/index'
export default {
    components: {
        toolbar,
        pag
    },
    props: {
        layout: String
    },
    data () {
        return {
            httpLock: false,
            readonly: false,
            rules: [
                { required: true, message: '这是必填项~', trigger: 'blur' }
            ],
            dialog: {
                title: '编辑',
                placeholder: '请输入添加的项目' || '添加多个值的话,用空格分开',
                input: null,
                provice: null
            },
            searchType: '1',
            query: {
                searchStr: '',
                pageNum: 1,
                pageSize: 20
            },
            add: true,
            provice: '',
            dialogTitle: '编辑',
            total: 0,
            textarea: null,
            inputVerify: true,
            dialogVisible: false,
            table_header: {
                城市档案: [
                    { label: '省份', prop: 'proviceName' },
                    { label: '城市', prop: 'name' }
                ],
                关注领域: [{ label: '关注领域', prop: 'areasName' }],
                所属行业: [{ label: '所属行业', prop: 'involvedName' }],
                主营范围: [{ label: '主营范围', prop: 'name' }],
                学校名称: [{ label: '学校名称', prop: 'name' }],
                所学专业: [{ label: '所学专业', prop: 'name' }],
                最高学历: [{ label: '最高学历', prop: 'name' }],
                举报原因: [{ label: '举报原因', prop: 'name' }],
                常见问题: [{ label: '常见问题', prop: 'content' }]
            },
            tableData: [],
            table_data: {
                城市档案: [
                    { provice: '广东', city: '广州', index: 0 },
                    { provice: '广东', city: '深圳', index: 1 },
                    { provice: '广西', city: '南宁', index: 2 },
                    { provice: '广西', city: '桂林', index: 3 }
                ],
                关注领域: [
                    { field: '数学', index: 0 },
                    { field: '文学', index: 1 },
                    { field: '医疗', index: 2 },
                    { field: '艺术', index: 3 }
                ],
                所属行业: [],
                主营范围: [
                    { scope: '导弹回收', index: 0 },
                    { scope: '航母维修', index: 1 },
                    { scope: '核弹翻新', index: 2 }
                ],
                学校名称: [],
                所学专业: [],
                最高学历: [],
                举报原因: [],
                常见问题: [
                    { content: '搞清楚自己的定位了吗', answer: '...' },
                    { content: '要饭吗', answer: '...' }
                ]
            },
            limit: [20, 6]
        }
    },
    computed: {
        /*         tableData: {
            get () {
                // return this.table_data[this.layout]
                return this.table_data[this.layout]
            },
            set (val) {
                return val
            }
        }, */
        tableHeader () {
            return this.table_header[this.layout] || []
        },
        selectItem () {
            return this.$refs.table.selection
                .map(v => v.index)
                .sort((a, b) => b - a)
        },
        tableKey () {
            if (this.layout === '城市档案') {
                return 'name'
            }
            return this.tableHeader.length ? this.tableHeader[0].prop : null
        },
        question () {
            return this.layout === '常见问题'
        }
    },
    watch: {
        layout () {
            this.$refs.table.selection.length = 0
            this.query.searchStr = ''
            this.Query()
        },
        searchType () {
            this.Query()
        }
    },
    created () {
        this.Query()
    },
    methods: {
        SelectUids (row = null) {
            return [].map.call(row ? [row] : this.$refs.table.selection, ({ code, uid }) => code || uid).join()
        },
        RowKey ({ code = null, uid = null }) {
            // console.log('key', row)
            return code || uid
        },
        Operator (ope) {
            const operator = {
                add: this.OpenDialog,
                del: this.Del,
                export: this.Export,
                exportAll: this.Export.bind(this, 'all')
            }
            return operator[ope]()
        },
        OpenDialog ({ row, column, $index = this.tableData.length } = {}) {
            console.log('布局', this.layout)
            this.limit = {
                城市档案: [10, 10],
                关注领域: [6],
                所属行业: [10],
                主营范围: [10],
                学校名称: [30],
                所学专业: [20],
                最高学历: [20],
                举报原因: [20],
                常见问题: [20000, 30]
            }[this.layout]
            this.dialogVisible = true
            this.inputVerify = true
            this.add = !row
            this.dialog = row
                ? {
                    title: '编辑 ' + this.layout,
                    placeholder: null,
                    input: this.layout === '常见问题' ? row.answer : row[this.tableKey],
                    provice:
                        this.layout === '常见问题' ? row.content : row.proviceName,
                    // index: $index,
                    proviceCode: row.proviceCode,
                    uid: row.uid,
                    code: row.code
                }
                : {
                    title: '新增 ' + this.layout,
                    // placeholder: this.layout === '常见问题' ? '请输入问题答案' : '添加多个值的话,用空格分开',
                    placeholder:
                        this.layout === '常见问题' ? '请输入问题答案' : '输入新增项',
                    input: null,
                    provice: null,
                    proviceCode: null,
                    uid: null,
                    code: null
                    // index: $index
                }
            // 无参数就是新增
            // console.log('操作', row, column, $index)
        },
        Close () {
            this.readonly = false
            this.dialog = {}
        },
        Confirm (operator, item) {
            // const h = this.$createElement
            // const _table = this.$refs.table.selection
            // const _child = this.table_header[this.layout].map(({ label, prop }) => h('el-table-column', { attrs: { label, prop } }))
            // console.log(_table, _child)
            return this.$msgbox({
                title: `将${operator}以下项目`,
                showCancelButton: true,
                cancelButtonText: '取消',
                confirmButtonClass: operator === '导出' ? '' : 'el-button--danger',
                // message: h('el-table', { attrs: { data: _table } }, _child)
                message: (
                    <el-table data={item || this.$refs.table.selection} max-height='600px' >
                        <el-table-column type='index' />
                        {this.table_header[this.layout].map(({ prop, label }) =>
                            <el-table-column prop={prop} label={label} />
                        )}
                    </el-table>
                )
            })
        },
        async Del ({ row, col, $index } = {}) {
            if (!(row || this.selectItem.length)) {
                return this.$message.warning('未选择删除项')
            }
            await this.Confirm('删除', row ? [row] : null)
            const data = {}
            if (this.layout === '城市档案') {
                data.code = this.SelectUids(row)
            } else {
                data.uids = this.SelectUids(row)
            }
            console.log('城市档案-删除', data)

            await HTTP(this.layout + 'Delete', data)
            this.$message.success('删除成功!')
            this.$refs.table.selection.length = 0
            this.Query()
        },
        Edit () {
            if (this.readonly) {
                this.dialogVisible = false
                return false
            }
            this.$refs.form.validate(result => {
                if (!result) return
                // console.log('dialog', this.dialog)
                // this.dialogVisible = false
                const _operator = this.add ? 'Add' : 'Update'
                let obj = {}
                // let list = []
                console.log(this.dialog)
                switch (this.layout) {
                case '城市档案':
                    obj = {
                        proviceName: this.dialog.provice,
                        proviceCode: this.dialog.proviceCode,
                        code: this.dialog.code,
                        name: this.dialog.input
                    }
                    break
                case '常见问题':
                    // console.log(this.layout)
                    obj = {
                        content: this.dialog.provice,
                        uid: this.dialog.uid,
                        answer: this.dialog.input
                    }
                    // obj.index = this.dialog.index
                    // this.dialog.code && (obj.code = this.dialog.code)
                    // list = [obj]
                    break

                default:
                    /*                     if (this.add) {
                    // 新增
                        list = this.dialog.input.match(/[^\r\n\s]+/g).map((v, i) => (
                            {
                                // index: i + this.tableData.index,
                                [this.tableKey]: v
                            }
                        ))
                    }
                    // this.table_data[this.layout][this.dialog.index] = { [this.tableKey]: this.dialog.input,   index: this.dialog.index }
                    // 编辑
                    obj = {
                        index: this.dialog.index,
                        uid: this.dialog.uid,
                        [this.tableKey]: this.dialog.input
                    } */
                    obj = {
                        [this.tableKey]: this.dialog.input,
                        uid: this.dialog.uid
                    }
                }
                if (this.layout === '常见问题') {
                    obj.type = this.searchType
                }
                // console.log(this.layout + _operator, obj)
                console.log('基础档案-修改', obj)

                !this.httpLock &&
                    HTTP(this.layout + _operator, obj)
                        .then(() => {
                            this.$message.success('数据已更新')
                            this.dialogVisible = false
                            this.Query()
                        })
                        .finally(() => (this.httpLock = false))
                this.httpLock = true
                /*                 if (this.add) {
                    // 新增
                    this.table_data[this.layout] = this.tableData.concat(list)
                    // eslint-disable-next-line no-useless-return
                    return
                } else {
                    this.$set(this.table_data[this.layout], obj.index, obj)
                } */
            })
        },
        async Export (param = '') {
            // console.log(this.$refs.table)
            if (!(this.$refs.table.selection.length || param)) {
                return this.$message.warning('亲~ 选中再导出吧')
            }
            const uids = param ? '' : this.SelectUids()
            param || await this.Confirm('导出')
            const { msg: name } = await HTTP(this.layout + 'exportExcel', { uids })
            this.$refs.table.selection.length = 0
            window.open(remote + 'common/download?fileName=' + name + '&delete=true')
            // HTTP('表格', { fileName: msg, delete: true })
        },
        PagChange ({ pageSize, pageNum }) {
            this.query = { ...this.query, pageSize, pageNum }
            this.Query()
        },
        Query () {
            const _name = this.layout
            const _append = _name === '常见问题' ? { type: this.searchType } : {}
            // console.log('查询:', this.query)
            HTTP(_name, { ...this.query, ..._append }).then(({ rows, total }) => {
                // console.log('%c' + this.layout, 'color:#259', rows)
                this.tableData = rows
                // this.table_data[_name] = rows
                this.total = total
            })
        },
        View (scope) {
            this.readonly = true
            this.OpenDialog(scope)
        }
    }
}
</script>

<style scoped lang="stylus">
.el-table
    ::v-deep .el-table__empty-block
        width auto !important
.padding
    padding 0 40px 50px 40px
    background #fff
.margin-bottom
    margin-bottom 10px
.column
    display flex
    flex-direction column
    .flex1
        flex 1
.dialog-title
    margin-bottom 2rem
</style>
